package com.ksm.zyz.controller;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ksm.zyz.common.base.BaseController;
import com.ksm.zyz.sys.entity.BaseSupplierInfo;
import com.ksm.zyz.sys.entity.ExtData;
import com.ksm.zyz.sys.entity.OrderGoodsList;
import com.ksm.zyz.sys.entity.xinXibiao;
import com.ksm.zyz.sys.serverentity.Tongbu;
import com.ksm.zyz.sys.serverentity.sOrderGoodsList;
import com.ksm.zyz.sys.serverservice.TongbuService;
import com.ksm.zyz.sys.serverservice.sBaseSupplierInfoService;
import com.ksm.zyz.sys.serverservice.sOrderGoodsListService;
import com.ksm.zyz.sys.serverservice.sXinXiBiaoService;
import com.ksm.zyz.sys.service.baseSupplierInfoService;
import com.ksm.zyz.sys.service.orderGoodsListService;

/**
 * @author liuhao
 *
 */
@Controller
@RequestMapping("tbclient")
public class SyncClientController extends BaseController<Tongbu>{
	@Autowired
	private sXinXiBiaoService xService;
	@Autowired
	private TongbuService Service;
	@Autowired
	private sBaseSupplierInfoService sBaseSupplierInfoService;
	@Autowired
	private baseSupplierInfoService BaseSupplierInfoService;
	@Autowired
	private sOrderGoodsListService sOrderGoodsListService;
	@Autowired
	private orderGoodsListService orderGoodsListService;
	 public static final String POST_URL = "http://192.168.124.24:8080/nbzapp/user/userLogin.do?";  

	 @SuppressWarnings("rawtypes")
	@RequestMapping(value ="cc")
	    @ResponseBody
		public ExtData tongbu(int ming){
		 try{
			 //数据包的封装
			 // 分为  添加数据 删除 数据  和修改数据
			 // 例：//map("insert",insertmap<"BaseSupplierInfo",List<BaseSupplierInfo>>)
			 
			 
			 Map<String,List> insertmap=new HashMap<String,List>();
			 Map<String,List> deletemap=new HashMap<String,List>();
			 Map<String,List> updatemap=new HashMap<String,List>();
			 
			 //BaseSupplierInfo
			 List<BaseSupplierInfo> insertBaseSupplierInfolist=new ArrayList<BaseSupplierInfo>();
			 List<BaseSupplierInfo> deleteBaseSupplierInfolist=new ArrayList<BaseSupplierInfo>();
			 List<BaseSupplierInfo> updateBaseSupplierInfolist=new ArrayList<BaseSupplierInfo>();
			 //OrderGoodsList
			 List<OrderGoodsList> insertOrderGoodsListlist=new ArrayList<OrderGoodsList>();
			 List<OrderGoodsList> deleteOrderGoodsListlist=new ArrayList<OrderGoodsList>();
			 List<OrderGoodsList> updateOrderGoodsListlist=new ArrayList<OrderGoodsList>();
			 
			 
			 List<Tongbu> tlist= Service.selectAllNew(0);
			 int size=tlist.size();
			 for(int i=0;i<size;i++)
			  {
			    String operate=tlist.get(i).getOperate();
				String Biaoming=tlist.get(i).getBiaoming();
				String idkey=tlist.get(i).getIdkey();
								
				if(".".equals(Biaoming))
				{
									}
				
			 else if("base_supplier_info".equals(Biaoming))
				{
					if("inserted".equals(operate))
					{ 
					  BaseSupplierInfo info=new BaseSupplierInfo();
					  //info.setOrderNum(idkey);
					  BaseSupplierInfo inf=BaseSupplierInfoService.selectInfo(info);
					  info.setSmId(ming);					  
					  insertBaseSupplierInfolist.add(info);
					}
					else if("delete".equals(operate))
					{
					  BaseSupplierInfo inf=new BaseSupplierInfo();
					  //info.setOrderNum(idkey);
					  inf.setSmId(ming);
					  deleteBaseSupplierInfolist.add(inf);
					}
					else if("updated".equals(operate))
					{
					  BaseSupplierInfo info=new BaseSupplierInfo();
					  //sinfo.setOrderNum(idkey);
					  BaseSupplierInfo inf=BaseSupplierInfoService.selectInfo(info);
					  info.setSmId(ming);
					  updateBaseSupplierInfolist.add(info);
					}
				}
				else if("order_goods_list".equals(Biaoming))
				{
					if("inserted".equals(operate))
					{ 
					  sOrderGoodsList sList=new sOrderGoodsList();
					  int id=Integer.parseInt(idkey);
					  sList.setId(id);
					  OrderGoodsList List=sOrderGoodsListService.selectInfo(sList);
					  List.setSmId(ming);
					  insertOrderGoodsListlist.add(List);
					}
					else if("delete".equals(operate))
					{
					  OrderGoodsList List=new OrderGoodsList();
					  int id=Integer.parseInt(idkey);
					  List.setId(id);
					  List.setSmId(ming);
					  deleteOrderGoodsListlist.add(List);
					}
					else if("updated".equals(operate))
					{
					  sOrderGoodsList sList=new sOrderGoodsList();
					  int id=Integer.parseInt(idkey);
					  sList.setId(id);
					  OrderGoodsList List=sOrderGoodsListService.selectInfo(sList);
					  List.setSmId(ming);
					  updateOrderGoodsListlist.add(List);
					}				
				}				
			  }
			 
			 if(insertBaseSupplierInfolist.size()!=0)
			 {
			 insertmap.put("BaseSupplierInfo", insertBaseSupplierInfolist);
			 }
			 if(deleteBaseSupplierInfolist.size()!=0)
			 {
			deletemap.put("BaseSupplierInfo", deleteBaseSupplierInfolist); 
			 }
			 if(updateBaseSupplierInfolist.size()!=0)
			 {
			updatemap.put("BaseSupplierInfo", updateBaseSupplierInfolist); 
			 }
			 
			 if(insertOrderGoodsListlist.size()!=0)
			 {
			 insertmap.put("OrderGoodsList", insertOrderGoodsListlist);
			 }
			 if(deleteOrderGoodsListlist.size()!=0)
			 {
			deletemap.put("OrderGoodsList", deleteOrderGoodsListlist); 
			 }
			 if(updateOrderGoodsListlist.size()!=0)
			 {
			updatemap.put("OrderGoodsList", updateOrderGoodsListlist); 
			 }
			 
			 
			 Map<String,Map> map=new HashMap<String, Map>();
			 if(insertmap.size()!=0)
			 map.put("insertmap", insertmap);
			 if(deletemap.size()!=0)
			 map.put("deletemap", deletemap);
			 if(updatemap.size()!=0)
			 map.put("updatemap", updatemap);
			 
			 System.out.println(map);
			 ObjectMapper mapper=new ObjectMapper();
	         String json1=mapper.writeValueAsString(map);
	         System.out.println(json1);
	         //String json=URLEncoder.encode(json1, "utf-8"); 
	         String json=new String(json1.getBytes("utf-8"),"utf-8"); 
	         System.out.println(json);
	         
	         List li=new ArrayList<Map>();
	         li.add(map);
	         extData.setList(li);
	         
			return extData;
		 }
				
		  catch (Exception e) {  
	            e.printStackTrace();  
	            return null;
	        }
		   
	              
		}
  public static void httpURLConnectionPOST (String parm1){
			   
				 try {  
			            URL url = new URL(POST_URL);  
			              
			            // 将url 以 open方法返回的urlConnection  连接强转为HttpURLConnection连接  (标识一个url所引用的远程对象连接)  
			            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中  
			              
			            // 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)  
			            connection.setDoOutput(true);  
			              
			            // 设置连接输入流为true  
			            connection.setDoInput(true);  
			              
			            // 设置请求方式为post  
			            connection.setRequestMethod("POST");  
			              
			            // post请求缓存设为false  
			            connection.setUseCaches(false);  
			              
			            // 设置该HttpURLConnection实例是否自动执行重定向  
			            connection.setInstanceFollowRedirects(true);  
			              
			            // 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)  
			            // application/x-javascript text/xml->xml数据 application/x-javascript->json对象 application/x-www-form-urlencoded->表单数据  
			            // ;charset=utf-8 必须要，不然妙兜那边会出现乱码【★★★★★】  
			            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");     
			              
			            // 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)  
			            connection.connect();   
			              
			            // 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)  
			            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());  
	                   //json 数据 
			              //封装
			            xinXibiao xinxi=new xinXibiao();
			            xinxi.setProvince(333333);
			            List<xinXibiao>   list= new ArrayList<xinXibiao>();
			            list.add(xinxi);
			            Map<String,Object> map=new HashMap<String, Object>();
			            map.put("xinxibiao", list);
			            ObjectMapper mapper=new ObjectMapper();
			            String json=mapper.writeValueAsString(map);
			            System.out.println(json);  
			            
			               // 解析
						Map<String,Object> map1=mapper.readValue(json, Map.class);
			            System.out.println(map1);
			            String json1=mapper.writeValueAsString(map1.get("xinxibiao"));
			            List<Object> xinxilist=mapper.readValue(json1,List.class);
			            System.out.println(xinxilist);
			            xinXibiao xinxi1=mapper.readValue(mapper.writeValueAsString(xinxilist.get(0)),xinXibiao.class);
			            System.out.println(xinxi1.toString());
			            // 格式 parm = aaa=111&bbb=222&ccc=333&ddd=444  
			           // String parm = app_key+ agt_num+ pid+ departid+ install_lock_name+ install_address+ install_gps+ install_work+ install_telete+ intall_comm;  
			            String parm ="phone=mahuan&password=123456";
			            // 将参数输出到连接  
			            dataout.writeBytes(parm);  
			              
			            // 输出完成后刷新并关闭流  
			            dataout.flush();  
			            dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)   
			              
//			            System.out.println(connection.getResponseCode());  
			              
			            // 连接发起请求,处理服务器响应  (从连接获取到输入流并包装为bufferedReader)  
			            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));   
			            String line;  
			            StringBuilder sb = new StringBuilder(); // 用来存储响应数据  
			              
			            // 循环读取流,若不到结尾处  
			            while ((line = bf.readLine()) != null) {  
//			                sb.append(bf.readLine());  
			                sb.append(line).append(System.getProperty("line.separator"));  
			            }  
			            bf.close();    // 重要且易忽略步骤 (关闭流,切记!)   
			            connection.disconnect(); // 销毁连接  
			            System.out.println(sb.toString());  
			      
			        } catch (Exception e) {  
			            e.printStackTrace();  
			        }  	 
						                       
			}   

}
